package middleware

import (
	"errors"
	"goadmin-huasen-portal/serializer"
	"goadmin-huasen-portal/util"

	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

type RecoverMiddleware struct {
}

func NewRecoverMiddleware() *RecoverMiddleware {
	return &RecoverMiddleware{}
}

func (m *RecoverMiddleware) Handle(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			if viper.Get("ENV") == "prod" {
				//TODO: send message to admin
				//kafka.Get().WriteMessage(viper.GetString("kafka.topic"), "panic", fmt.Sprintf("[Panic] %v", err))
			}
			util.Log().Panic("recovered from panic: ", err)
			c.JSON(500, serializer.ErrorResponse(errors.New("服务器开小差啦,稍后再来试一试")))
		}
	}()
	c.Next()
}
